package com.bwjf.dzfp.common.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.mail.util.MailSSLSocketFactory;

public class SendEmailUtils {

	private static String protocol = "smtp"; // 协议

	// 用户名密码验证，需要实现抽象类Authenticator的抽象方法PasswordAuthentication
	static class MyAuthenricator extends Authenticator {
		String u = null;
		String p = null;

		public MyAuthenricator(String u, String p) {
			this.u = u;
			this.p = p;
		}

		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(u, p);
		}
	}

	private String to; // 收件人

	public SendEmailUtils(String to) {
		this.to = to;
	}

	public boolean send(MailSenderInfo mailSenderInfo, File pdfFile) {
		Properties prop = new Properties();
		// 协议
		prop.setProperty("mail.transport.protocol", protocol);
		// 服务器
		prop.setProperty("mail.smtp.host", mailSenderInfo.getMailServerHost());
		// 端口
		prop.setProperty("mail.smtp.port", mailSenderInfo.getMailServerPort());
		// 使用smtp身份验证
		prop.setProperty("mail.smtp.auth", "true");
		// 使用SSL，企业邮箱必需！
		// 开启安全协议
		MailSSLSocketFactory sf = null;
		try {
			sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
		} catch (GeneralSecurityException e1) {
			e1.printStackTrace();
		}
		prop.put("mail.smtp.ssl.enable", "true");
		prop.put("mail.smtp.ssl.socketFactory", sf);
		//
		Session session = Session.getInstance(prop, new MyAuthenricator(
				mailSenderInfo.getUserName(), mailSenderInfo.getPassword()));
		session.setDebug(true);
		MimeMessage mimeMessage = new MimeMessage(session);
		try {
			mimeMessage.setFrom(new InternetAddress(mailSenderInfo
					.getFromAddress(), "中石油电子发票平台"));
			mimeMessage.addRecipient(Message.RecipientType.TO,
					new InternetAddress(to));
			Multipart mainPart = new MimeMultipart();
			// 创建一个包含HTML内容的MimeBodyPart
			BodyPart html = new MimeBodyPart();
			// 设置HTML内容
			html.setContent(mailSenderInfo.getContent(),
					"text/html; charset=utf-8");
			mainPart.addBodyPart(html);
			mimeMessage.setSubject("中石油电子发票");
			mimeMessage.setSentDate(new Date());
			/**
			 * mimeMessage.setText("您在XXX使用了密码重置功能，请点击下面链接重置密码:\n" +
			 * "http://localhost:8080/XXX/ResetPassword?id=" + id);
			 **/
			if (pdfFile != null) {
				BodyPart attachmentBodyPart = new MimeBodyPart();
				DataSource source = new FileDataSource(pdfFile);
				attachmentBodyPart.setDataHandler(new DataHandler(source));

				// 网上流传的解决文件名乱码的方法，其实用MimeUtility.encodeWord就可以很方便的搞定
				// 这里很重要，通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
				// sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
				// messageBodyPart.setFileName("=?GBK?B?" +
				// enc.encode(attachment.getName().getBytes()) + "?=");

				// MimeUtility.encodeWord可以避免文件名乱码
				attachmentBodyPart.setFileName(MimeUtility
						.encodeWord("电子发票.pdf"));
				mainPart.addBodyPart(attachmentBodyPart);
			}

			// 将multipart对象放到message中
			mimeMessage.setContent(mainPart);
			mimeMessage.saveChanges();
			Transport.send(mimeMessage);
			return true;
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static void main(String[] args) {
		SendEmailUtils s = new SendEmailUtils("970451049@qq.com");
		// s.send(mailSenderInfo, new File("D:\test\1.pdf"));
	}
}
